package com.shujia.flink.core

import org.apache.flink.api.common.eventtime.WatermarkStrategy
import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.connector.kafka.source.KafkaSource
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer
import org.apache.flink.contrib.streaming.state.EmbeddedRocksDBStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._

/**
 * 聚合计算时保证结果正确性
 */
object Demo9KafkaExactlyOnceOnAGG {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    // 每 100-0ms 开始一次 checkpoint
    env.enableCheckpointing(20000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    //EXACTLY_ONCE: 数据处理的唯一一次
    //AT_LEAST_ONCE: 至少一次，可能会重复
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃， 如果计算的状态很大，checkpoint需要更多的时间
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 允许两个连续的 checkpoint 错误
    env.getCheckpointConfig.setTolerableCheckpointFailureNumber(2)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
    env.getCheckpointConfig.setExternalizedCheckpointCleanup(
      ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)

    //指定checkpoint 将状态保存的位置（hdfs）
    env.getCheckpointConfig.setCheckpointStorage("hdfs://master:9000/flink/checkpoint")

    //状态后端：
    //HashMapStateBackend先包状态存储在taskManager的内存中，checkpoint时将状态持久化到hdfs
    //env.setStateBackend(new HashMapStateBackend())


    //EmbeddedRocksDBStateBackend: 先将状态保存再taskManager的磁盘上，checkpoint时再将状态持久化到hdfs
    env.setStateBackend(new EmbeddedRocksDBStateBackend())

    /**
     * HashMapStateBackend:先放内存，效率高，状态如果太大内存会放不下
     * EmbeddedRocksDBStateBackend： 先放磁盘，不受状态大小的限制，效率第
     */


    //先创建topic
    //kafka-topics.sh --create --zookeeper master:2181,node1:2181,node2:2181/kafka --replication-factor 2 --partitions 2 --topic exactly
    val source: KafkaSource[String] = KafkaSource
      .builder[String]
      .setBootstrapServers("master:9092,node1:9092,node2:9092") //kafka集群列表
      .setTopics("exactly") //topic
      .setGroupId("Demo9KafkaExactlyOnceOnAGG") //消费者组
      .setStartingOffsets(OffsetsInitializer.earliest()) //读取数据的位置
      .setValueOnlyDeserializer(new SimpleStringSchema()) //反序列化类
      .build

    //构建DataStream
    val kafkaSource: DataStream[String] = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source")

    val kvDS: DataStream[(String, Int)] = kafkaSource.flatMap(_.split(",")).map((_, 1))

    val countDS: DataStream[(String, Int)] = kvDS.keyBy(_._1).sum(1)

    countDS.print()

    env.execute()

  }

}
